/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.chatapp;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.NotFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 * This Class Create the functionalities of IntantMessage.
 * @author Group C
 */
/**
 * @author Charles
 *
 */
public class ImpInstantMessage implements InstantMessage
{
    //Create a XMMP conection to server XMPP
   private XMPPConnection connection=null;
   private static ImpInstantMessage instantMessage=null;
   private HashMap hm = new HashMap();
   private PacketFilter filter = null; 
   private MultiUserChat chat = null;
   private PacketListener listen=null;
   //Logger for ImpInstantMessage
   private final static Logger log = Logger.getLogger(ImpInstantMessage.class);
    
    /**
     * Contructor of InstantMessage class
     */
    private ImpInstantMessage(){}
    
    
    /**
     * This method follows the Singleton Patern, ensure only one instance and 
     * provide a global point of acces to that instance.
     * @return instantMessage
     */
    public static synchronized ImpInstantMessage getIntanceMessage()
    {
        if(instantMessage==null)
        {
            instantMessage=new ImpInstantMessage();
        }
        return instantMessage;
    }
    /**
     * This method create a login conection in the personal count of XMPP googleTalk
     * @param userName
     * @param password
     * @throws XMPPException 
     * 
     */
    public boolean login(String userName, String password) 
    {
        boolean loginOK=true;
        
        ConnectionConfiguration config=new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
        connection=new XMPPConnection(config);
        
        
        try {
            connection.connect();
        } catch (XMPPException ex) {
            //Logger.getLogger(ImpInstantMessage.class.getName()).log(Level.SEVERE, null, ex);
            log.warn("User cannot connect in the XMMP System");
        }
        
        try {
            connection.login(userName, password);
            filter = new AndFilter(new PacketTypeFilter(Message.class),new NotFilter(new FromContainsFilter(connection.getUser())));
            listen = (PacketListener) new ImpListener();
            connection.addPacketListener(listen,filter);
            
            //Creat a multichat session
            chat = new MultiUserChat(connection, "Busqueda");
            
            //Shows the user connection in the XMMP systmem
            log.info("you are connected like: "+connection.getUser());
        
        } catch (XMPPException ex) {
            loginOK=false;
            log.warn("User cannot logging in the XMMP System");
        }
        
        return loginOK;
    }
     /**
     * Disconect the XMPP user
     */
    public void logout()
    {
        if(connection!=null)
        {
            connection.disconnect();
            log.info("User "+connection.getUser()+"has finished the session");
        }
    }
    /**
     * This method create a chat to specific person and send the message 
     * @param message to send
     * @param to is a contact 
     * @throws XMPPException 
     */
    public void sendMessageSearchProfile(String Content) 
    {
       ArrayList<String> contactos=ImpInstantMessage.getIntanceMessage().contacList();
       contactos.add("usuariopruebagrupoc@gmail.com");
        
        Message msg = new Message();
         
        for(int i=0; i<contactos.size(); i++)
        {
        	ImpSearchProfile searchProfile= new ImpSearchProfile(Content, contactos.get(i));
        	msg.setTo(contactos.get(i)); 
            msg.setProperty("Type", searchProfile);
            
            try {
            	System.out.println(contactos.get(i)+"eeeeeeeeeeeee");
                chat.sendMessage(msg);
            } catch (XMPPException ex) {
                log.warn("Cleint cannot send the SearchProfile Message");
            }
        }
        
    }
    
    /**
     * 
     * 
     */
    public void sendMessageUserContent(int IDUser, String addressUser, String URLContent, String to) 
    {
       //chat = new MultiUserChat(connection, "UserContent");        
        
        Message msg = new Message();
        
        ImpUserContent userContent= new ImpUserContent(IDUser,addressUser,URLContent,null,to);
        msg.setTo(to); 
      
        msg.setProperty("Type", userContent);
        
        try {
            chat.sendMessage(msg);
        } catch (XMPPException ex) {
            log.warn("Client cannot send the UserContent Message");
        }
    }
    
    /**
     * 
     */
    public void sendMessageSearchResult(ImpSearchResult result, String to) 
    {
       //chat = new MultiUserChat(connection, "Respuesta");        
        
        Message msg = new Message();
        msg.setTo(to); 
        msg.setProperty("Type", result);
        
        try {
            chat.sendMessage(msg);
        } catch (XMPPException ex) {
            log.warn("Client cannot send the SearchResult Message");
        }
    }
    /**
     * This method return an Arraylist of contacts
     * @return a ArrayList of Contacts
     */
    public ArrayList<String> contacList()
    {
        //Obtain a conctact list in this conection
        ArrayList<String> contactos=new ArrayList<String>();
        
        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        
        //Print a contact list 
        for (RosterEntry r : entries) 
        {
            contactos.add(r.getUser());     
        }
        System.out.println(contactos.size());
        
        return contactos;
    }
   
    /**
     * This method obtain and show a contact list of the XMPP user
     */
    public void displayContactList()
    {
        //Obtain a conctact list in this connection
        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        
        //Print message "Contact List"
        log.info("\n\n" + entries.size() + " Contact list: ");
      
        
        //Print a contact list 
        for (RosterEntry r : entries) 
        {
            System.out.println(r.getUser());
        }
    }
   
    
    public boolean isConnect(){
        
        if(this.connection.isConnected()) return true;
        
        else return false;
    }
    
    public boolean searchContent(String content)
    { 
              
       if(hm.containsKey(content))
           return true;
               
        return false;
    }
    
    public ArrayList <ImpContent> getContent(String id){
        
        ArrayList <ImpContent> result = new ArrayList<ImpContent>();
        ImpContent contenido = new ImpContent();
                
                String name = (String) hm.get(id);
           
                contenido.setNamePhoto(name);
        result.add(0,contenido );
        
        return result;
    }
    
    
    public void addHash(){
        hm.put("leon","Africa.jpg");
        hm.put("ballena","Viaje.jpg");
    }
}
